
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props
import akka.pattern.ask
import scala.concurrent._
import akka.util.Timeout
import scala.concurrent.duration._

case class Work(start : Int, end : Int, length : Int);
case class Stop();
case class Done();

class Manager extends Actor {
  
  var doneCount = 0
  var workers = 0;
  var workSize = 500000;
  
  def receive = {
    case Work(start, end, length) => 
      {
	    workers = (end / workSize).toInt
	    
	    for (i <- 0 to workers - 1)
	    {
	      val w = context.system.actorOf(Props[Worker], name = "w" + i)
	      if (i == 0)
	    	w ! Work(1, workSize, length)
		  else
		  {
		    w ! Work(((workSize * i) + 1), (workSize * (i + 1)), length)
		  }
	    }
      }
    case Done =>
      {
        doneCount = doneCount + 1
        if (doneCount == workers)
        {
          context.system.shutdown()
        }
      }
  }
}

class Worker extends Actor {
  def receive = {
    case Work(start, end, length) => 
      {
        for (i <- start to end)
		{
		    var sum = 0;
		    for (j <- i to (i + (length - 1)))
		    {
		      sum = sum + (j * j)
		    }
		    
		    val result = Math.sqrt(sum);
		    val myInt = result.toInt
		    
		    val sum2 = myInt * myInt
		    
		    if (sum == sum2)
		    {
		      println(i);
		    }
		}
        sender ! Done;
      }
  }
}

object Main extends App {
  
  
  val system = ActorSystem("HelloSystem")
  val mgr = system.actorOf(Props[Manager], name = "mgr")
  val startTime = System.currentTimeMillis();
  mgr ! Work(1, 1000000, 4)
  
  system.awaitTermination()
  
  val endTime   = System.currentTimeMillis();
  val totalTime = (endTime - startTime);
  println("Time: " + totalTime + " ms");
}